package com.ddtj.demo1.service.impl;

import com.ddtj.demo1.entity.User;
import com.ddtj.demo1.dao.UserJpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.List;

public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    UserJpa userJpa;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = new User();
        user.setUsername(username);
        Example<User> userExample = Example.of(user);
        List<User> all = userJpa.findAll(userExample);
        if(null == all || all.size() ==0){
            throw new UsernameNotFoundException("用户不存在");
        }
        String encode = passwordEncoder.encode(all.get(0).getPassword());
        org.springframework.security.core.userdetails.User user1 = new org.springframework.security.core.userdetails.User(username, encode,
                AuthorityUtils.createAuthorityList("admin"));
        return user1;
    }
}
